package com.laiketui.order.runner;

import com.laiketui.order.service.OrderProcessService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class OrderCancelRunner implements CommandLineRunner {

    private static final String ORDER_CANCEL_QUEUE = "order_cancel_queue";
    private static final int ORDER_CANCEL_DAYS = 7;
    private static RBlockingDeque<String> queue;
    private static RDelayedQueue<String> delayedQueue;


    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private OrderProcessService orderProcessService;


    @Override
    public void run(String... args) throws Exception {
       new Thread(this::start).start();
    }

    private void start() {
        queue = redissonClient.getBlockingDeque(ORDER_CANCEL_QUEUE);
        delayedQueue = redissonClient.getDelayedQueue(queue);
        String orderParentNo=null;
        while (true) {
            try {
                if (Objects.isNull(queue)) {
                    queue = redissonClient.getBlockingDeque(ORDER_CANCEL_QUEUE);
                    delayedQueue = redissonClient.getDelayedQueue(queue);
                }
                orderParentNo = queue.take();
                log.info("开始取消订单:{}", orderParentNo);
                orderProcessService.cancelOrder(orderParentNo,"超时未付款，订单已取消");
            } catch (Exception e) {
                log.error("取消订单失败:{}  原因:{}",orderParentNo,e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public static void addOrderCancel(String orderParentNo) {

        try {
            delayedQueue.offer(orderParentNo, ORDER_CANCEL_DAYS, TimeUnit.DAYS);
            log.info("添加取消订单:{}", orderParentNo);
        } catch (Exception e) {

        }
    }
    public static void removeOrderCancel(String orderParentNo) {
        try {
            delayedQueue.remove(orderParentNo);
            log.info("移除取消订单:{}", orderParentNo);
        } catch (Exception e) {

        }
    }
}
